package com.xinzhidi.common.model;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author cx
 * 保护性暂停设计模式 结果收集类
 * @date 2023/09/21
 */
@Slf4j
public class ReportResultGuarded<T> {

    /**
     * 线程数 默认1
     */
    private int threadNum = 1;

    /**
     * 当前完成的线程数原子
     */
    private final AtomicInteger currentThreadNum = new AtomicInteger(0);

    private ReportResultGuarded() {
    }

    public ReportResultGuarded(Integer threadNum) {
        this.threadNum = threadNum;
    }

    /**
     * 结果集
     */
    private final List<T> resultList = new ArrayList<>();

    /**
     * get方法，等待线程结果
     *
     * @return java.util.List<com.chcontrol.core.model.vo.EquipmentWarnExcelZHVO>
     * @author Mr_Fei
     * @date 2020/8/28 11:06
     */
    @SneakyThrows
    public List<T> getResultList() {
        synchronized (this) {
            while (currentThreadNum.get() != threadNum) {
                this.wait();
            }
            return this.resultList;
        }
    }

    /**
     * 完成线程数+1，并合并结果集
     *
     * @param resultList 单线程的结果集
     * @author Mr_Fei
     * @date 2020/8/28 11:07
     */
    public void setResultList(List<T> resultList) {
        synchronized (this) {
            this.resultList.addAll(resultList);
            //当前完成线程数+1；
            this.currentThreadNum.getAndIncrement();
            if (currentThreadNum.get() == threadNum) {
                this.notifyAll();
            }
        }
    }

    /**
     * 完成线程数+1，并合并结果集
     *
     * @param resultObj 单线程的结果集
     * @author Mr_Fei
     * @date 2020/8/28 11:07
     */
    public void addResult(T resultObj) {
        synchronized (this) {
            this.resultList.add(resultObj);
            //当前完成线程数+1；
            this.currentThreadNum.getAndIncrement();
            if (currentThreadNum.get() == threadNum) {
                this.notifyAll();
            }
        }
    }
}